package com.mirror.tk.core.log.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import javax.annotation.Resource;

import com.mirror.tk.core.log.service.LogWork;
import com.mirror.tk.core.module.sys.domain.SysOlog;
import com.mirror.tk.core.module.sys.service.SysOlogService;

public class DBLogWork extends TimerTask implements LogWork {

	@Resource
	private SysOlogService sysOlogService;
	
	private List<SysOlog> list = new ArrayList<SysOlog>();
	private int limit = 0;
	private int seconds = 10;
	private long time = 0;
	private Timer timer = new Timer();

	public void init() {
		timer.schedule(this, seconds * 1000, seconds * 1000);
	}

	public void destroy() {
		timer.cancel();
	}

	@Override
	public void doWork(SysOlog sysOlog) {

		synchronized (list) {
			list.add(sysOlog);
			if (list.size() >= limit) {
				batchInsert();
			}
		}
		
	}

	private void batchInsert() {
		List<SysOlog> paramList = new ArrayList<SysOlog>();
		synchronized (list) {
			paramList.addAll(list);
			list.clear();
		}
		time = System.currentTimeMillis();
		new Thread(new WorkThread(sysOlogService, paramList)).start();
	}

	@Override
	public void run() {
		if (list.size() >= 1 && System.currentTimeMillis() - time >= 1000 * seconds) {
			batchInsert();
		}
	}

	public int getLimit() {
		return limit;
	}

	public void setLimit(int limit) {
		this.limit = limit;
	}

	public int getSeconds() {
		return seconds;
	}

	public void setSeconds(int seconds) {
		this.seconds = seconds;
	}

	
	private class WorkThread implements Runnable {

		private SysOlogService sysOlogService;
		private List<SysOlog> list;

		private WorkThread(SysOlogService sysOlogService, List<SysOlog> list) {
			this.sysOlogService = sysOlogService;
			this.list = list;
		}

		@Override
		public void run() {
			sysOlogService.saves(list);
		}
	}
	
}
